import React, { useState, useEffect } from 'react'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { QRCodeSVG } from 'qrcode.react'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { Typography, message, Button } from 'antd'
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons'
import { useT, createEvent } from '@designable/event-system'
import { useForm } from '@formily/react'

export interface QRCodeProps {
  /** QR码内容 */
  contentValue?: string
  /** QR码尺寸 */
  size?: number
  /** 错误纠正级别 */
  level?: 'L' | 'M' | 'Q' | 'H'
  /** 前景色 */
  fgColor?: string
  /** 背景色 */
  bgColor?: string
  /** 是否包含边距 */
  includeMargin?: boolean
  /** 边距大小 */
  marginSize?: number
  /** 图片设置 */
  imageSettings?: {
    src: string
    height: number
    width: number
    excavate: boolean
  }
  /** 样式 */
  style?: React.CSSProperties
  'data-designer-node-id'?: string
}

export const QRCode: React.FC<QRCodeProps> = (props) => {
  const $t = useT()
  const form = useForm()
  const {
    contentValue = 'https://example.com',
    size = 128,
    level = 'M',
    fgColor = '#000000',
    bgColor = '#FFFFFF',
    includeMargin = true,
    marginSize = 4,
    imageSettings,
    style,
    'data-designer-node-id': designerNodeId,

    ...rest
  } = props
  console.log('props', props)

  // 处理表达式输入的值
  const [qrValue, setQrValue] = useState<string>('https://example.com')

  useEffect(() => {
    const processValue = async () => {
      if (!contentValue) return

      try {
        const result = await createEvent(contentValue, { form, $t })
        setQrValue(typeof result === 'string' ? result : String(result))
      } catch (error) {
        console.warn('QR码表达式执行失败:', error)
        setQrValue(contentValue)
      }
    }

    processValue()
  }, [contentValue, form, $t])

  const downloadQR = () => {
    const svgElement = document.getElementById('QRCode') as unknown as SVGElement
    if (svgElement) {
      // 将 SVG 转换为 Canvas
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()

      // 设置 canvas 尺寸
      canvas.width = size + (includeMargin ? marginSize * 2 : 0)
      canvas.height = size + (includeMargin ? marginSize * 2 : 0)

      // 设置背景色
      if (ctx) {
        ctx.fillStyle = bgColor
        ctx.fillRect(0, 0, canvas.width, canvas.height)

        // 将 SVG 转换为 DataURL
        const svgData = new XMLSerializer().serializeToString(svgElement)
        const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' })
        const svgUrl = URL.createObjectURL(svgBlob)

        img.onload = () => {
          // 绘制 SVG 到 Canvas
          ctx.drawImage(img, 0, 0)

          // 创建下载链接
          const link = document.createElement('a')
          link.href = canvas.toDataURL('image/png')
          link.download = '二维码.png'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)

          // 清理 URL
          URL.revokeObjectURL(svgUrl)
        }

        img.src = svgUrl
      }
    }
  }


  return (
    <div style={style} data-designer-node-id={designerNodeId}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ marginBottom: '20px' }}>
          <CopyToClipboard text={qrValue}>
            <Typography.Link onClick={() => message.success($t('复制成功'))}>
              {qrValue}
              <CopyOutlined />
            </Typography.Link>
          </CopyToClipboard>
        </div>
        <div style={{ marginBottom: '20px' }}>
          <QRCodeSVG
            value={qrValue}
            size={size}
            level={level}
            fgColor={fgColor}
            bgColor={bgColor}
            includeMargin={includeMargin}
            marginSize={marginSize}
            imageSettings={imageSettings}
            id="QRCode"
            {...rest}
          />
          <div>
            <Typography.Text type="danger">
              {$t('该二维码仅用于手机微信/浏览器扫码查看详情')}
            </Typography.Text>
          </div>
        </div>

        <Button
          onClick={downloadQR}
          type="primary"
          icon={<DownloadOutlined />}
        >
          {$t('下载二维码')}
        </Button>
      </div>
    </div>
  )
}

